<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var data = [
      {
        id: "01",
        pid: "",
        name: "老王",
        children: []
      },
      {
        id: "02",
        pid: "01",
        name: "小张",
        children: []
      },
      {
        id: "03",
        pid: "02",
        name: "小xx",
        children: []
      }
    ]
    function toTree(data) {
      let cloneData = JSON.parse(JSON.stringify(data))    // 对源数据深度克隆
      let tree = cloneData.filter((father) => {              //循环所有项
        let branchArr = cloneData.filter((child) => {
          return father.id == child.pid;//返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.children = branchArr; //如果存在子级，则给父级添加一个children属性，并赋值
        }
        return father.pid == 0;//返回第一层
      });
      return tree;    //返回树形数据
    }
    var tree = toTree(data);
    console.log(tree);
  </script>
</body>

</html>